using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class UImSelects<T> : MonoBehaviour where T : Component {

	public GameObject targetChildren;
	
	protected List<T> listComponents;
	
	protected T activeComponent;
	
	protected void Start() {
		InitComponents();
	}
	
	virtual protected void InitComponents() {
		if(targetChildren == null) {
			targetChildren = gameObject;
		}
		
		listComponents = ComponentUtils.getChildrenComponentSort<T>(targetChildren);
		
		foreach(T component in listComponents) {
			if(isSelected(component)) {
				if(activeComponent == null) {
					activeComponent = component;
					
				} else {
					setSelected(component, false);
				}
			}
		}
		
		if(activeComponent == null && listComponents.Count > 0) {
			activeComponent = listComponents[0];
			setSelected(activeComponent, true);
		}
	}
	
	virtual protected bool isSelected(T component) {
		return true;
	}
	
	virtual protected void setSelected(T component, bool status) {
	}
	
	virtual public bool setSelectedIndex(int index) {
		if(listComponents == null || index < 0 || index >= listComponents.Count) {
			return false;
			
		} else {
			T component = listComponents[index];
			if(component == activeComponent) {
				return false;
			}
			
			setSelected(activeComponent, false);
			activeComponent = component;
			setSelected(activeComponent, true);
			return true;
		}
	}
}

